// 路由守卫
import router from '@/router/index'
import 'element-ui/lib/theme-chalk/index.css'
import NProgress from 'nprogress'
import '@fortawesome/fontawesome-free/css/all.min.css'
import 'nprogress/nprogress.css'
import {fnAddDynamicMenuRoutes} from '@/router/getAsyncRouter'
import store from '@/store/index.js'
import { getMenu, filterMenu } from '@/api/menu'
 
NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
})
// 白名单
const whiteList = ['/home','/'] // no redirect whitelist
 
// 导航守卫
router.beforeEach((to, from, next) => {
    NProgress.start()
    try {
        // console.log(store.state.dynamicRoutes)
        // console.log(router.getRoutes())
        // 判断是否已经获取过动态菜单，未获取，则需要获取一次
        if (store.state.dynamicRoutes.length === 0 & sessionStorage.getItem('token') !== null) {
            if (whiteList.indexOf(to.path) !== -1) {
                next()
            } else {
                getMenu().then(res => {
                    if (res.code === 200) {
                        let menuRouter = fnAddDynamicMenuRoutes(filterMenu(res.data))
                        store.dispatch('dynamicRoutes', menuRouter).then(() => {
                            store.state.dynamicRoutes.forEach(item => {
                                router.addRoute('home', item)
                            })
                            next({...to, replace: true})
                        })
                    } else {
                        next({path: '/'})
                    }
                })
            }
        } else {
            if (to.meta.requireAuth) {
                // 判断该路由是否需要登录权限
                if (sessionStorage.getItem('token') !== null) {
                    // 判断本地是否存在token
                    next()
                    // 这里是待会获取异步路由的地方
                } else {
                    // 未登录,跳转到登陆页面
                    next({
                        path: '/'
                    })
                }
            } else {
                if (whiteList.indexOf(to.path) !== -1) {
                    next()
                } else {
                    if (sessionStorage.getItem('token') !== null) {
                        // 判断本地是否存在token
                        // next(`/?redirect=${to.path}`)
                        next()
                    } else {
                        next(`/?redirect=${to.path}`)
                    }
                }
            }
        }
    } catch (error) {
        next(`/?redirect=${to.path}`)
    }
})
 
router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})